package com.xiaozhengkeji.springboot.frame.easy.api;

import com.xiaozhengkeji.springboot.frame.easy.Bean.QueryInfo;
import com.xiaozhengkeji.springboot.frame.easy.Bean.ResponseBean;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysGoods;
import com.xiaozhengkeji.springboot.frame.easy.service.SysGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodSApi {
    @Autowired
    private SysGoodsService sysGoodsService;

    /*创建新商品*/
    @PostMapping("/add")
    @PreAuthorize("hasRole('ROLE_admin')")
    public ResponseBean addGood(@RequestBody SysGoods sysGoods) {
        if (sysGoodsService.insert(sysGoods) == null) {
            return new ResponseBean(500, "添加失败", null);
        }
        return new ResponseBean(200, "添加成功", null);
    }

    /*修改商品*/
    @PutMapping("/edit")
    @PreAuthorize("hasRole('ROLE_admin')")
    public ResponseBean editGood(@RequestBody SysGoods sysGoods) {
        if (sysGoodsService.update(sysGoods) == null) {
            return new ResponseBean(500, "修改失败", null);
        }
        return new ResponseBean(200, "修改成功", null);
    }

    /*获取全部商品*/
    @GetMapping("/all")
    @PreAuthorize(value = "isAuthenticated()")
    public ResponseBean allGood(QueryInfo queryInfo) {
        int numbers = sysGoodsService.queryAll(new SysGoods()).size();// 获取数据总数
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize(); //页码
        List<SysGoods> goodsbases = sysGoodsService.queryAllByLimit(pageStart, queryInfo.getPageSize());
        return new ResponseBean(numbers, "ok", goodsbases);
    }

    /*获取单独商品*/
    @GetMapping("/info")
    @PreAuthorize(value = "isAuthenticated()")
    public ResponseBean Good(@RequestParam("id") Integer id) {
        return new ResponseBean(200, "ok", sysGoodsService.queryById(id));
    }

    /*删除商品*/
    @DeleteMapping("/delete")
    @PreAuthorize("hasRole('ROLE_admin')")
    public ResponseBean deleteGood(@RequestParam("id") Integer id) {
        if (sysGoodsService.deleteById(id)) {
            return new ResponseBean(200, "success", null);
        }
        return new ResponseBean(500, "error", null);
    }
}
